#!/usr/bin/env python
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# Descripttion:
# version: 0.0.1
# Author: Wenwei Fu (2516800961@qq.com)
# FilePath: /fastapi_byd/app/api/routes/expert.py
# Create: 2021-01-04 16:37:40
# LastAuthor: Wenwei Fu
# lastTime: 2021-01-10 15:01:42
# --------------------------------------------------------

import cv2
import numpy as np
import ast
from app.db.schemas import Traffic_Cameras

west = [[367, 622], [1497, 602], [1469, 506], [662, 524]]
east = [[310, 654], [1490, 659], [1428, 563], [629, 559]]
north = [[620, 703], [1436, 675], [1360, 547], [876, 562]]
south = [[448, 613], [1370, 612], [1300, 463], [769, 465]]

north_south_dst = [[0, 2708], [1842, 2708], [1842, 0], [0, 0]]
west_east_dst = [[0, 1842], [2708, 1842], [2708, 0], [0, 0]]

def coordinate_trans(point, destination):
  if destination == 'south':
    src = np.float32(np.array(south))
    dst = np.float32(np.array(north_south_dst))
  elif destination == 'north':
    src = np.float32(np.array(north))
    dst = np.float32(np.array(north_south_dst))
  elif destination == 'west':
    src = np.float32(np.array(west))
    dst = np.float32(np.array(west_east_dst))
  elif destination == 'east':
    src = np.float32(np.array(east))
    dst = np.float32(np.array(west_east_dst))

  prespective_transform = cv2.getPerspectiveTransform(src, dst)

  p1 = np.float32(np.array([[point]]))
  p1 = cv2.perspectiveTransform(p1, prespective_transform)[0][0]

  x = 0
  y = 0
  if destination == 'south':
    x = p1[0]
    y = p1[1]
  elif destination == 'north':
    x = 1842 - p1[0]
    y = 2708 - p1[1]
  elif destination == 'west':
    x = 1842 - p1[1]
    y = p1[0]
  elif destination == 'east':
    x = p1[1]
    y = 2708 - p1[0]

  return (x, y)

async def pixel_trans_geo(pixel_coor, camera_id):
    # 查询摄像头方位
    camera_info_query = Traffic_Cameras.get(Traffic_Cameras.camera_id == camera_id)
    camera_info = camera_info_query.__data__
    camera_direction = camera_info['camera_position']
    # 将 像素坐标字符串 转化成 list
    coordinate_list = ast.literal_eval(pixel_coor)
    print('摄像机信息：', coordinate_list, camera_direction)
    results = []
    for item in coordinate_list:
        coordinate = list(item.values())
        print('坐标值：', coordinate)
        results.append(list(coordinate_trans(coordinate, camera_direction)))
    return str(results)
